#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      shoo
#
# Created:     12/06/2011
# Copyright:   (c) shoo 2011
# Licence:     <your licence>
#-------------------------------------------------------------------------------

import mail_addr
import inline_img
import logging
import re
import os
import base64
from google.appengine.api import mail
from google.appengine.ext import db

logging.getLogger().setLevel(logging.DEBUG)

ATTACH_URL_PREFIX="https://pc.dwmail.jp"

# ドコモwebメールの内容をAppEngineからメールで送信する
class RcvForwarder:
    def __init__(self, sender, to, openner, image_link, subject_prefix="", subject_suffix=""):
        self.sender = sender
        self.to= to
        self.openner= openner
        self.image_link= image_link
        self.subject_prefix= subject_prefix
        self.subject_suffix= subject_suffix

    def forward(self, mailDic):
        param={}
        param['sender'] = self.sender
        param['to']=self.to
        subject = re.sub(r'<[^>]+>',u'[絵文字]', mailDic['subject'])
        param['subject'] = self.subject_prefix + subject + self.subject_suffix
        body=mailDic['body']
        if isHtml(body):    # 必ずTrue
            param['html']=self.replaceImage(self.mailHeader(mailDic, True)+body)
        else:
            param['body']=self.mailHeader(mailDic, False)+body

        if "attach" in mailDic:
            param['attachments']=[]
            for url, name in mailDic['attach']:
                # logging.debug(url)
                res = self.openner.open(ATTACH_URL_PREFIX+url, {})
                param['attachments'].append((name, res.content))

        email = mail.EmailMessage(**param)
        email.send()

    # from,to,cc,bcc情報をメールの先頭に記述
    def mailHeader(self, dic, isHtml):
        fromlist = [mail_addr.get_name_addr(addr) for addr in dic['from']]
        tolist = [mail_addr.get_name_addr(addr) for addr in dic['to']]
        r=""
        r+="From: "+', '.join(fromlist)+"\r\n"
        r+="To  : " + ', '.join(tolist)+"\r\n"
        if "cc" in dic:
            cclist = [mail_addr.get_name_addr(addr) for addr in dic['cc']]
            r+="Cc  : "+', '.join(cclist)+"\r\n"
        if "bcc" in dic:
            bcclist = [mail_addr.get_name_addr(addr) for addr in dic['bcc']]
            r+="Bcc : "+', '.josin(bcclist)+"\r\n"

        r+=u"日時: %d/%2d/%2d %2d:%02d:%02d" % dic['date'][:6]
        if isHtml:
            r = r.replace("<", "&lt;").replace("<","&gt;")
            r=u"件名: "+dic['subject']+"\r\n" + r
            r = r'<pre style="font-family:monospace">'+r+"</pre>"

        logging.debug(r)
        return r

    # 絵文字・デコメ絵文字画像がドコモwebメールへリンクになっているので書き換える
    def url2data(self, match):
        r = match.group()
        img_url = match.group(1)
        if not img_url.startswith('http'):
            if img_url.startswith('/ai/'):
                img_url = ATTACH_URL_PREFIX+img_url
            else:
                # src="javascript:void(false);"となっていてブラウザ上でも表示されない
                return r
        if self.image_link:
            # App Engineにリンク
            key = re.sub(r'.+/','',img_url)
            img = inline_img.Image.get_by_key_name(key)
            if not img:
                res = self.openner.open(img_url, {})
                img = inline_img.Image(key_name=key, data=res.content, content_type=res.headers['content-type'].split(';')[0])
                img.put()
            src = "http://"+os.environ['APPLICATION_ID'].replace("s~","")+".appspot.com/img?k="+key
        else:
            # data:image/～,base64,～　の形式で埋め込む
            # Gmailだと表示されないので上のリンク形式を推奨
            res = self.openner.open(img_url, {})
            src = "data:"+res.headers["content-type"].split(";")[0]+";base64,"+base64.b64encode(res.content)

        r = r.replace(match.group(1), src)
        return r

    def replaceImage(self,html):
        pattern = re.compile(r'<img[^>]+src="([^\"]+)"[^.]*>')
        return pattern.sub(self.url2data, html)

# htmlメールかどうか
def isHtml(content):
    # すべてのメールはHTMLに変換されている
    return True


def main():
    pass

if __name__ == '__main__':
    main()
